<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { updateDictionaryCategoryApi, getSuccessStatus } from '@/api/dictionary'

const props = defineProps<{
	editRow: { [key: string]: any }
}>()

const formInstance = ref<FormInstance | null>(null)

const initState = {
	categoryName: '',
	categoryTitle: '',
}
const state = ref<ObjType>(initState)

const formLayout = {
	style: 'margin: 0 10px',
	labelWidth: 'auto',
	labelPosition: 'left',
}

const rules = {
	categoryName: [{ required: true, message: '请输入字典类别名称！', trigger: 'change' }],
	categoryTitle: [{ required: true, message: '请输入字典类别标题！', trigger: 'change' }],
}

async function formCommit() {
	try {
		await formInstance.value?.validate()
		const res = await updateDictionaryCategoryApi([{ ...props.editRow, ...state.value }])
		if ((res.code = getSuccessStatus())) {
			return true
		}
	} catch (error) {
		console.log(error)
	}
}

function init() {
	formInstance.value?.resetFields()
	state.value = initState
	Object.keys(state.value).forEach((k) => {
		state.value[k] = props.editRow[k]
	})
}

defineExpose({
	init,
	formCommit,
})
</script>

<template>
	<el-form :model="state" :rules="rules" v-bind="formLayout" ref="formInstance">
		<el-row :gutter="24">
			<el-col :span="12">
				<el-form-item prop="categoryName" label="类别名称">
					<el-input v-model="state.categoryName" placeholder="类别名称必须唯一" allowClear />
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item prop="categoryTitle" label="类别标题">
					<el-input v-model="state.categoryTitle" placeholder="请输入类别标题" allowClear />
				</el-form-item>
			</el-col>
		</el-row>
	</el-form>
</template>
